<template>
  <transition name="fade">
    <div class="custom-preloader" v-if="show">
      <div class="backdrop" v-if="showBackDrop"></div>
      <div class="content" :class="{'inline-text': text && inLine}">
        <img src="./loading.png" alt="">
        <p class="loading-p" v-if="text">{{text}}</p>
      </div>
    </div>
  </transition>
</template>

<script>
  export default {
    name: "preloader",
    data () {
      return {
        show: false,
        duration: 0,
        showBackDrop: true,
        text: null,
        inLine: false
      }
    },
    watch: {
      show (val) {
        if (val && this.duration > 0) this.handleClose()
      }
    },
    methods: {
      handleClose () {
        const timeId = setTimeout(() => {
          this.show = false
          const timeId2 = setTimeout(() => {
            this.$el.parentNode.removeChild(this.$el);
            clearTimeout(timeId2)
          }, 501);
          clearTimeout(timeId)
        }, this.duration)
      }
    }
  }
</script>

<style scoped lang="scss">
  .custom-preloader {
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    z-index: 99999;
    .backdrop {
      width: 100%;
      height: 100%;
      background: rgba(0,0,0,.5);
    }
    .content {
      padding: 30px 40px;
      background: #fff;
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      border-radius: 10px;
      text-align: center;
      &.inline-text {
        display: flex;
        align-items: center;
        img {
          width: 25px;
          height: 25px;
          margin-right: 20px;
        }
        .loading-p {
          padding-top: 0;
        }
      }
      img {
        display: block;
        margin: 0 auto;
        width: 70px;
        height: 70px;
        animation: rotate 1.5s infinite linear;
      }
      .loading-p {
        padding-top: 10px;
      }
    }
  }

  @keyframes rotate {
    from {
      transform: rotate(0);
    }

    to {
      transform: rotate(360deg);
    }
  }
  .fade-enter-active, .fade-leave-active {
    transition: opacity .5s;
  }
  .fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
    opacity: 0;
  }
</style>
